<?php
if(!isset($_GET['id'])){
    echo "ID不能为空";
    die;
}
?>

<!DOCTYPE html>
<html>
<head>
    <script src="<?php echo includes_url( '/js/')."jquery-3.5.1.min.js";?>"></script>
    <style type="text/css">
        *{
            -webkit-box-sizing: border-box;
        }
        div#featured_img img{
            width: 100px;
            height: auto;
            float: left;
            margin-right: 10px;
            margin-bottom: 10px;
            border: none;
            opacity: 1;
        }
        table{
            border-collapse:collapse;
        }
        table tr th{
            text-align: center;
        }
        table tr th,td{
            border: 1px solid #000;
            padding: 3px;
        }
        #save:hover{
            cursor: pointer;
        }
        .tags ul{
            display: inline-block;
        }
        .tags ul li{
            float: left;
            margin-right: 5px;
        }
        .img-preview img {
            width: 300px;
        }
        #search-box{
            position: absolute;
            z-index: 99;
            background-color: white;
            box-shadow: 0 3px 6px rgba(0, 0, 0, 0.3);
        }
        #search-box .close {
            position: absolute;
            top: -10px;
            right: -7px;
            z-index: 100;
            background-color: #45c6f1;
            width: 20px;
            height: 20px;
            border-radius: 100%;
            text-align: center;
            font-size: 20px;
        }
        #search-box .close:hover{
            cursor: pointer;
        }
        #search-box .tip{
            width: 200px;
            height: 80px;
            line-height: 80px;
            text-align: center;
        }
        #search-box ul{
            max-height: 360px;
            overflow: auto;
        }
        #search-box ul li{
            list-style: none;
            border-bottom: 1px solid #b0b3b4;
            padding: 3px;
            display: flex;
        }
        #search-box ul li:hover{
            background-color: #f1f1f1;
            cursor: pointer;
        }
        #search-box ul li img{
            width: 60px;
            height: 60px;
        }
    </style>
</head>
<body>
<?php
$id = $_GET['id'];

global $wpdb;
$fpv = $wpdb->get_results("select * from spider_fpv where id=" . $id)[0];

$photos = empty($fpv->photos) ? [] : explode(',',$fpv->photos);
$parts = empty($fpv->parts) ? [] : explode('@@@', $fpv->parts);

?>

<div class="wrap">
    <!--    独立的fpv_id   -->
    <input type="hidden" name="fpv_id" id="fpv_id" value="<?php echo $fpv->wp_posts_id; ?>">

    <!--    独立的文章编辑区域   -->
    <?php if ($fpv->wp_posts_id==0){ ?>
    <div id="article">
        <h1 class="wp-heading-inline">缩略图</h1>
        <div class="img-preview">
            <img src="<?php echo includes_url()."/images/blank.gif"; ?>">
        </div>
        <div id="featured_img">
                <?php foreach ($photos as $photo) { ?>
                    <img src="<?php echo $photo.tinyjpg(); ?>">
                <?php } ?>
                <div style="clear: both;"></div>
                <input type="text" name="featured_img" style="display: none;">

                <?php if(empty($photos)){ ?><input type="text" name="add-img"><button id="add-img">添加图片</button><?php } ?>
        </div>
        <h1 class="wp-heading-inline">标题</h1>
        <div id="title"><input type="text" name="title"></div>
        <h1 class="wp-heading-inline">分类</h1>
        <?php
        $terms = get_terms(array(
            'taxonomy' => 'category',
            'hide_empty' => false,
        ));
        ?>
        <div>
            <select id="category">
                <?php foreach ($terms as $term) { ?>
                    <option name="category_id" value="<?php echo $term->term_id; ?>" <?php if($term->slug=='build'){ ?>selected="selected"<?php } ?>><?php echo $term->name; ?></option>
                <?php } ?>
            </select>
        </div>
        <?php
        $tags = get_terms(array(
            'taxonomy' => 'post_tag',
            'hide_empty' => false,
        ));
        ?>
        <div class="tags">
            <ul>
                <?php foreach ($tags as $tag) { ?>
                    <li><input type="checkbox" name="tags" value="<?php echo $tag->name; ?>" /><?php echo $tag->name; ?></li>
                <?php } ?>
            </ul>
        </div>
        <h1 class="wp-heading-inline">正文</h1>
        <div>
            <?php wp_editor( $fpv->content, 0, $settings = array() ); ?>
            <button id="save" class="button button-hero">发布文章</button>
        </div>
    </div>
    <?php } ?>

    <h1 class="wp-heading-inline">配件</h1>
    <!--    配置  -->
    <table id="parts">
        <tr>
            <th>原始类型名</th>
            <th>类型名</th>
            <th>名称</th>
            <th>图片预览</th>
            <th>配置信息</th>
            <th>操作</th>
        </tr>
        <?php
        global $wpdb;
        //获取所有part类型
        $types = $wpdb->get_results("select id,type,name,origin_name from parts_type");
        ?>

        <?php if ($fpv->wp_posts_id==0){ //如果wp_posts_id == 0,则【新增】配置清单?>

            <?php foreach ($parts as $i => $part) { ?>
            <?php  $p = explode('|||', $part);   ?>
            <tr>
                <input type="hidden" name="id">

                <td><?php echo $p[0]; ?></td>
                <td>
                    <select>
                        <?php
                        foreach ($types as $type){
                        ?>
                        <option value ="<?php echo $type->id; ?>"><?php echo $type->origin_name." | ".$type->name ?></option>
                        <?php } ?>
                    </select>
                </td>
                <td>
                    <input type="hidden" name="origin_url" value="<?php echo $p[2]; ?>">
                    <a href="https://google.com/search?tbm=isch&q=<?php echo urlencode($p[1]); ?>" target="_blank"><?php echo $p[1]; ?></a>
                    <div><input id="name-search_<?echo $i; ?>" type="text" name="name" placeholder="配件名称"></div>
<!--                    <div id="search-box">-->
<!--                        <ul>-->
<!--                            <li><img src="/wp-content/uploads/2021/02/parts_601ac4795ecab.jpg"><p>房间里的手机发了快速的减肥了</p></li>-->
<!--                            <li><img src="/wp-content/uploads/2021/02/parts_601ac4795ecab.jpg"><p>房间里的手机发了快速的减肥了</p></li>-->
<!--                            <li><img src="/wp-content/uploads/2021/02/parts_601ac4795ecab.jpg"><p>房间里的手机发了快速的减肥了</p></li>-->
<!--                        </ul>-->
<!--                    </div>-->
                </td>
                <td>
                    <div><img id="img_preview" src="#" width="100" height="100"></div>
                    <div><input type="text" name="img" placeholder="配件图片"></div>
                </td>
                <td>
                    <div>链接：<input type="text" name="url" placeholder="（选填）"><a href="https://s.taobao.com/search?search_type=item&q=<?php echo urlencode($p[1]); ?>" target="_blank">搜淘宝</a></div>
                    <div>价格：<input type="text" name="price" placeholder="（选填）"></div>
                </td>
                <td>
                    <BUTTON id="save-parts" class="button">保存零件</BUTTON>
                </td>
            </tr>
            <?php } ?>
        <?php } ?>

        <?php if ($fpv->wp_posts_id>0){ //如果wp_posts_id > 0,则【编辑】配置清单?>
            <?php
            global $wpdb;
            $fpv_parts = $wpdb->get_results("select parts.*,parts_type.name as part_name from fpv_parts 
                                                                    left join parts on parts.id=fpv_parts.parts_id
                                                                    left join parts_type on parts_type_id=parts_type.id
                                                                    where fpv_id=".$fpv->wp_posts_id." 
                                                                    order by sort ASC");

            foreach ($fpv_parts as $fp){
            ?>
                <tr>
                    <input type="hidden" name="id" value="<?php echo $fp->id; ?>">

                    <td><?php echo $fp->part_name; ?></td>
                    <td>
                        <select>
                            <?php
                            foreach ($types as $type){
                                ?>
                                <option value ="<?php echo $type->id; ?>" <?php if($type->id==$fp->parts_type_id){ ?>selected="selected"<?php } ?>><?php echo $type->origin_name." | ".$type->name ?></option>
                            <?php } ?>
                        </select>
                    </td>
                    <td>
                        <input type="hidden" name="origin_url" value="<?php echo $fp->origin_url; ?>">
                        <a href="https://google.com/search?tbm=isch&q=<?php echo urlencode($fp->name); ?>" target="_blank"><?php echo $fp->name; ?></a>
                        <div><input id="name-search_<?echo $i; ?>" type="text" name="name" placeholder="配件名称" value="<?php echo $fp->name; ?>"></div>
                    </td>
                    <td>
                        <div><img id="img_preview" src="<?php echo $fp->img; ?>" width="100" height="100"></div>
                        <div><input type="text" name="img" placeholder="配件图片" value="<?php echo $fp->img; ?>"></div>
                    </td>
                    <td>
                        <div>链接：<input type="text" name="url" placeholder="（选填）" value="<?php echo $fp->url; ?>"><a href="https://s.taobao.com/search?search_type=item&q=<?php echo urlencode($fp->name); ?>" target="_blank">搜淘宝</a></div>
                        <div>价格：<input type="text" name="price" placeholder="（选填）" value="<?php echo $fp->price; ?>"></div>
                    </td>
                    <td>
                        <BUTTON id="save-parts" class="button">保存零件</BUTTON>
                    </td>
                </tr>
            <?php } ?>
        <?php } ?>
    </table>

    <div><button class="button button-hero button-primary" id="save-build-list">保存配置清单</button></div>
</div>


<script type="text/javascript">
    function isNull(data) {
        return (data == "" || data == undefined || data == null) ? true : false;
    }

    $("#featured_img img").click(function(){
        _img_url = $(this).attr('src');
        $("input[name='featured_img']").val(_img_url);
        $(this).siblings("img").each(function () {
            $(this).css({"opacity":"1"});
        });
        $(this).css({"opacity":"0.5"});
        $(".img-preview img").attr("src",_img_url);
    });

    $("#save").click(function(){
        _img_url = $("input[name='featured_img']").val();
        _title = $("input[name='title']").val();
        _term_id = $("#category").find("option:selected").val();
        _tags = $("checkbox[name='tags']").val();
        checkTag = [];//定义一个空数组
        $("input[name='tags']:checked").each(function(i){//把所有被选中的复选框的值存入数组
            checkTag[i] =$(this).val();
        });

        _photos =  [];
        $("#featured_img").children("img").each(function (i){
            _photos[i] = $(this).attr('src')
        })

        var wp_editor_id = $(".wp-editor-area").attr('id');
        var content;
        var editor = tinyMCE.get(wp_editor_id);
        if (editor) {
            _content = editor.getContent();
        } else {
            _content = $('#' + wp_editor_id).val();
        }

        if(isNull(_img_url)){
            alert("[缩略图]不能为空");
            return false;
        }
        if(isNull(_title)){
            alert("[标题]不能为空");
            return false;
        }
        if(isNull(checkTag)){
            alert("[标签]不能为空");
            return false;
        }

        _data = {
            'spider_fpv_id':<?php echo $id; ?>,
            'title':_title,
            'img':_img_url,
            'category_id':_term_id,
            'content':_content,
            'tags_input':checkTag.join(","),
            'photos':_photos.join(",")
        };

        $.ajax({
            url: "<?php echo site_url(); ?>/wp-json/fpvone/v1/fpv-post",
            type: "POST",
            data: _data,
            dataType: "JSON" ,
            success : function(data) {
                data = JSON.parse(data);
                if(data.code == 1){
                    alert(data.msg)
                    $("#fpv_id").val(data.post_id)
                    $("div#article").css("display","none");
                }else{
                    alert(data.msg)
                }
            }
        });
    });

    $("#add-img").click(function () {
        _img = $("input[name='add-img']").val();
        _data = {
            'img':_img
        };
        if (isNull(_img)){
            alert("add-img不能为空");
            return false;
        }
        $.ajax({
            url: "<?php echo site_url(); ?>/wp-json/fpvone/v1/add-img",
            type: "POST",
            data: _data,
            dataType: "JSON" ,
            success : function(data) {
                data = JSON.parse(data);
                if(data.code == 1){
                    alert(data.msg);
                    $("input[name='featured_img']").val(data.url);
                    $(".img-preview img").attr("src",data.url);
                }else{
                    alert(data.msg);
                }
            }
        });
    });

    //默认匹配type
    function match_all_types() {
        $('#parts tr').each(function () {
            _name = $(this).children("td:first").text();
            // console.log(_name);
            if(!isNull(_name)){

                _option_list = $(this).children("td:first").next().find("option");

                //遍历option值并且匹配
                _option_list.each(function () {
                    if($(this).text().search(_name)>=0){
                        $(this).attr("selected",true);
                        $(this).siblings().attr("selected",false);
                        // console.log(_name+"  匹配  "+$(this).text())
                    }
                });

            }

        })
    }
    $(document).ready(function () {

        match_all_types();

        window.onbeforeunload = function(event) { return confirm("确定离开此页面吗？"); }

        $('[id=save-parts]').on('click',function () {
            _id = $(this).parent().parent().find("input[name='id']").val();
            _type = $(this).parent().parent().find("option:selected").val();
            _name = $(this).parent().parent().find("input[name='name']").val();
            _img = $(this).parent().parent().find("input[name='img']").val();
            _origin_url = $(this).parent().parent().find("input[name='origin_url']").val();
            _url = $(this).parent().parent().find("input[name='url']").val();
            _price = $(this).parent().parent().find("input[name='price']").val();
            if(isNull(_type)){
                alert("[类型]不能为空");
                return false;
            }
            if(isNull(_name)){
                alert("[名称]不能为空");
                return false;
            }
            if(isNull(_img)){
                alert("[图片]不能为空");
                return false;
            }
            _data = {
                'id': _id,
                'type': _type,
                'name': _name,
                'img': _img,
                'origin_url': _origin_url,
                'url': _url,
                'price': _price,
            };
            console.log(_data);

            _this = $(this);

            _this.text('保存中...');
            $.ajax({
                url: "<?php echo site_url(); ?>/wp-json/fpvone/v1/save-parts",
                type: "POST",
                data: _data,
                dataType: "JSON" ,
                success : function(data) {
                    data = JSON.parse(data);
                    if(data.code == 1){
                        console.log(data);
                        _this.parent().parent().find("input[name='id']").val(data.id);
                        _this.parent().parent().find("#img_preview").attr("src",data.img);
                        _this.parent().parent().find("input[name='url']").val(data.url);
                    //      清除图片地址输入框
                    //     _this.parent().parent().find("input[name='img']").hide();
                    }else{
                        alert(data.msg);
                    }
                },
                complete : function (XMLHttpRequest, textStatus) {
                    _this.text('保存零件');
                }
            });
        });

        $("#save-build-list").on('click',function () {

            var _ids = new Array();
            $('#parts tr').each(function () {
                _id = $(this).find("input[name=id]").val();
                if(!isNull(_id)){
                    _ids.push(_id);
                }
            });

            _fpv_id = $("#fpv_id").val();
            if(isNull(_fpv_id)){
                alert("请先发布文章");
                return false;
            }

            _data = {
                'ids': _ids.join(","),
                'fpv_id':_fpv_id
            };

            $.ajax({
                url: "<?php echo site_url(); ?>/wp-json/fpvone/v1/save-build-list",
                type: "POST",
                data: _data,
                dataType: "JSON" ,
                success : function(data) {
                    data = JSON.parse(data);
                    if(data.code == 1){
                        console.log(data);
                        alert(data.msg);
                    }else{
                    }
                }
            });
        });

        //==============================下拉模糊搜索==================

        var _html_not_found = "<div id='search-box'><div class='tip'>NOT FOUND</div><div class='close'>&times;</div></div>";
        var _html_searching = "<div id='search-box'><div class='tip'>搜索中🔍</div><div class='close'>&times;</div></div>";

        var search_data = [];

        $("input[id^=name-search_]").keydown(function(event){
            if(event.keyCode==13){

                var curValue = $(this).val();

                if (!isNull(curValue)){
                    _this = $(this);
                    //隐藏之前的弹框
                    clear_tip();
                    //显示正在搜索中
                    _this.parent().after(_html_searching);
                    //清空之前的search_data
                    search_data = [];

                    _data = {
                        "name":curValue
                    };
                    $.ajax({
                        url: "<?php echo site_url(); ?>/wp-json/fpvone/v1/search-parts",
                        type: "POST",
                        data: _data,
                        dataType: "JSON" ,
                        success : function(data) {
                            //清空当前的tip弹框
                            clear_tip();

                            data = JSON.parse(data);
                            if(data.code == 1){
                                data = data.data;
                                if(data.length == 0){
                                    //空结果
                                    _this.parent().after(_html_not_found);
                                }else{
                                    //保存到全局供之后使用
                                    search_data = data;

                                    //拼装结果
                                    html = '<div id="search-box"><ul>';
                                    for (var i=0;i<data.length;i++) {
                                        html += '<li><img src="'+data[i].img+'"><p>'+data[i].name+'</p></li>';
                                    }
                                    html += '</ul><div class="close">&times;</div></div>';
                                    _this.parent().after(html);
                                }

                            }else{

                            }
                        }
                    });
                }
            }
        });

        function clear_tip(){
            $("[id=search-box]").each(function () {
                $(this).hide();
            });
        }

        //  关闭tip弹窗
        $(document).on('click', '.close', function(){
            search_data = [];
            clear_tip();
        });

        $(document).on('click', '#search-box ul li', function(){
            i = $(this).index();
            //填充数据
            $(this).parent().parent().parent().parent().find("input[name='id']").val(search_data[i].id);
            $(this).parent().parent().parent().parent().find("select").val(search_data[i].parts_type_id);
            $(this).parent().parent().parent().parent().find("input[name='name']").val(search_data[i].name);
            $(this).parent().parent().parent().parent().find("input[name='img']").val(search_data[i].img);
            $(this).parent().parent().parent().parent().find("input[name='origin_url']").val(search_data[i].origin_url);
            $(this).parent().parent().parent().parent().find("input[name='url']").val(search_data[i].url);
            $(this).parent().parent().parent().parent().find("input[name='price']").val(search_data[i].price);
            $(this).parent().parent().parent().parent().find("#img_preview").attr("src",search_data[i].img);
            search_data = [];
            clear_tip();
        });
    });
</script>
</body>
</html>

